package sz.szsmk.citizencard.ui.newversion.activity

import android.content.Intent
import android.os.Bundle
import android.text.Editable
import android.text.Selection
import android.text.TextUtils
import android.text.TextWatcher
import android.widget.EditText
import android.widget.TextView
import androidx.recyclerview.widget.LinearLayoutManager
import com.chenenyu.router.Router
import com.chenenyu.router.annotation.Route
import com.gyf.immersionbar.ktx.immersionBar
import kotlinx.android.synthetic.main.activity_bind_cash_card.*
import sz.szsmk.citizencard.DaggerApplication
import sz.szsmk.citizencard.R
import sz.szsmk.citizencard.model.network.bean.response.BaseBean
import sz.szsmk.citizencard.model.network.bean.response.CheckBankCodeRes
import sz.szsmk.citizencard.model.network.dzbean.res.GetBankNameRes
import sz.szsmk.citizencard.model.network.dzbean.res.SupportBankResponse
import sz.szsmk.citizencard.mvp.BasePresenter
import sz.szsmk.citizencard.ui.dzsmkavtivity.AppBaseActivity
import sz.szsmk.citizencard.ui.dzsmkavtivity.AppendRealNameInfoActivity
import sz.szsmk.citizencard.ui.newversion.activity.adapter.BindBankCardAdapter
import sz.szsmk.citizencard.ui.newversion.activity.presenter.BindBankCardPresenter
import sz.szsmk.citizencard.ui.newversion.activity.view.BindBankCardMvpView
import sz.szsmk.citizencard.ui.newversion.config.Constants
import sz.szsmk.citizencard.util.ACache
import javax.inject.Inject

/**
 *  author : hyt
 *  date : 2020/10/19
 *  description : 绑定银行卡 第一步 选择银行输入卡号
 */

@Route(Constants.BINDBANKCARDACTIVITY)
class BindBankCardActivity: AppBaseActivity(), BindBankCardMvpView {

    @Inject
    lateinit var bindBankCardPresenter: BindBankCardPresenter

    override fun getTopTitle() = null
    var bindBankCardAdapter:BindBankCardAdapter ?= null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        component.inject(this)
        setContentView(R.layout.activity_bind_cash_card)

        immersionBar{
            reset()
            statusBarColor(R.color.white)
            fitsSystemWindows(true)  //使用该属性,必须指定状态栏颜色
            statusBarDarkFont(true)
        }

        bindBankCardPresenter.getOpenId(ACache.get(DaggerApplication.getIns()).getAsString("access_token"))
        bankCardNumAddSpace(et_bankCardNumber, null)
        initView()
        initEvent()
    }

    override fun initPresenters(): Array<BasePresenter<*>>? {
        return arrayOf(bindBankCardPresenter)
    }

    private fun initView(){
        rv_supportBank.layoutManager = LinearLayoutManager(this)
        bindBankCardAdapter = BindBankCardAdapter()
        rv_supportBank.adapter = bindBankCardAdapter

        //手动写入数据   有个接口返回 有时候会提示 签名错误
        var bankList = mutableListOf<SupportBankResponse.DataBean>()
        var bank1 = SupportBankResponse.DataBean()
        bank1.bankName = "中国银行"
        bank1.bankIconUrl = "http://zhszyfb2020.szsmk.com/images/firsthotsales/20201020/18440ae9-778e-4681-bd15-3c249f4c94f2.png"
        bank1.bankCode = "0001"
        bankList.add(bank1)

        var bank2 = SupportBankResponse.DataBean()
        bank2.bankName = "工商银行"
        bank2.bankIconUrl = "http://zhszyfb2020.szsmk.com/images/firsthotsales/20201020/c491bf8d-b6aa-4455-9c6f-c67e23be89ad.png"
        bank2.bankCode = "0002"
        bankList.add(bank2)

        var bank3 = SupportBankResponse.DataBean()
        bank3.bankName = "建设银行"
        bank3.bankIconUrl = "http://zhszyfb2020.szsmk.com/images/firsthotsales/20201020/fac65033-4b25-4766-b178-3c4351244e08.png"
        bank3.bankCode = "0008"
        bankList.add(bank3)

        var bank4 = SupportBankResponse.DataBean()
        bank4.bankName = "农业银行"
        bank4.bankIconUrl = "http://zhszyfb2020.szsmk.com/images/firsthotsales/20201020/08d12d66-aaa0-4255-ae08-43c0c4481544.png"
        bank4.bankCode = "0012"
        bankList.add(bank4)

        bindBankCardAdapter?.setNewData(bankList)

    }

    override fun getSupportBankSuccess(response: SupportBankResponse) {
//        var newList = mutableListOf<SupportBankResponse.DataBean>()
//        for(temp in response.data){
//            if(temp.bankName=="中国银行" ||temp.bankName=="建设银行"||temp.bankName=="工商银行"||temp.bankName=="农业银行"){
//                newList.add(temp)
//            }
//        }
//        response.data = newList
//        bindBankCardAdapter?.setNewData(response.data)
    }

    override fun checkBankCardNumberValidationSuccess(response: CheckBankCodeRes) {

        val bankCode: String = bindBankCardAdapter?.getBankCode()!!
        ACache.get(this).remove("bankCode")
        ACache.get(this).put("bankCode", bankCode)
        ACache.get(this).put("bankCardNumber", et_bankCardNumber.text.toString().trim())


        val intent = Intent(this, AppendRealNameInfoActivity::class.java)
        intent.putExtra("type", 0)
        startActivityForResult(intent, 123)

    }

    override fun getBankNameSuccess(getBankNameRes: GetBankNameRes) {
    }

    override fun onFail(baseBean: BaseBean) {
        showToast(baseBean.message)
    }

    private fun initEvent(){
        back.setOnClickListener { finish() }
        btn_nextStep.setOnClickListener {
            if(bindBankCardAdapter?.getCheckItem()==null){
                showToast("请选择银行")
                return@setOnClickListener
            }
            if(TextUtils.isEmpty(et_bankCardNumber.text.toString())){
                showToast("请输入卡号")
                return@setOnClickListener
            }
            if(!cb_agreement.isChecked){
                showToast("请勾选协议")
                return@setOnClickListener
            }

            //南京银行 默认000001      建设银行默认000003   现在没有南京银行
            //所以 后续操作 都是000003
            ACache.get(this).put("channelId", "000003")
            bindBankCardAdapter?.getCheckItem()?.bankCode?.let { it1 ->
                bindBankCardPresenter.checkBankCardNumberValidation(
                        et_bankCardNumber.text.toString().replace(" ", ""), it1)
            }

        }

        tv_agreement.setOnClickListener {
            Router.build("wordshow").with("word_name", "jianshe_argeement").go(this)
        }
    }


    private fun bankCardNumAddSpace(mEditText: EditText, carSub_tv: TextView?) {
        mEditText.addTextChangedListener(object : TextWatcher {
            var beforeTextLength = 0
            var onTextLength = 0
            var isChanged = false
            var location = 0 // 记录光标的位置
            private var tempChar = charArrayOf()
            private val buffer = StringBuffer()
            var konggeNumberB = 0
            override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {
                beforeTextLength = s.length
                if (buffer.length > 0) {
                    buffer.delete(0, buffer.length)
                }
                konggeNumberB = 0
                for (i in 0 until s.length) {
                    if (s[i] == ' ') {
                        konggeNumberB++
                    }
                }
            }

            override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {
                onTextLength = s.length
                buffer.append(s.toString())
                if (onTextLength == beforeTextLength || onTextLength <= 3 || isChanged) {
                    isChanged = false
                    return
                }
                isChanged = true
            }

            override fun afterTextChanged(s: Editable) {
                if (carSub_tv != null) {
                    carSub_tv.text = mEditText.text
                }
                if (isChanged) {
                    location = mEditText.selectionEnd
                    var index = 0
                    while (index < buffer.length) {
                        if (buffer[index] == ' ') {
                            buffer.deleteCharAt(index)
                        } else {
                            index++
                        }
                    }
                    index = 0
                    var konggeNumberC = 0
                    while (index < buffer.length) {
                        if (index == 4 || index == 9 || index == 14 || index == 19 || index == 24 || index == 29) {
                            buffer.insert(index, ' ')
                            konggeNumberC++
                        }
                        index++
                    }
                    if (konggeNumberC > konggeNumberB) {
                        location += konggeNumberC - konggeNumberB
                    }
                    tempChar = CharArray(buffer.length)
                    buffer.getChars(0, buffer.length, tempChar, 0)
                    var str = buffer.toString()
                    if (location > str.length) {
                        location = str.length
                    } else if (location < 0) {
                        location = 0
                    }
                    if (str.length >= 23) {
                        str = str.substring(0, 23)
                        location = str.length
                    }
                    mEditText.setText(str)
                    val etable = mEditText.text
                    Selection.setSelection(etable, location)
                    isChanged = false
                }
            }
        })
    }
}